package com.study.gulimallproduct.exception;

import com.study.common.exception.BizCodeEnum;
import com.study.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @description TODO
 * @date 2023/11/19 11:10
 */

@Slf4j
/* @author zheng
* @date 2023/11/19 11:11
* @ControllerAdvice
* @ResponseBody
**/
@RestControllerAdvice(basePackages = "com.study.gulimallproduct.controller")
public class GulimallExceptionControllerAdvice {

//    这是一个精确异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){

        log.error("数据校验出现问题{}，异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(item->{
            //item.getField()校验错误的字段，item.getDefaultMessage()字段错误的提示
            errorMap.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",errorMap);
    }

//    直接编写一个全局异常，未知错误全部由该异常抛出
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable t){
        log.error("数据校验出现问题{}，异常类型{}",t.getMessage(),t.getClass());
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
